// Copyright (c) 2025 Huawei Technologies Co., Ltd.
// openUBMC is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//         http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
//
// Description: 管理KVM心跳报文发送

#include "HeartbeatManager.hpp"

HeartbeatManager::HeartbeatManager(boost::asio::io_context& io_context, std::chrono::seconds interval, HeartbeatCallback callback)
    : timer_(io_context), interval_(interval), callback_(std::move(callback)) {
    PackData pack_data;
    heartbeat_message_ = pack_data.KvmHeartBeat();
}

void HeartbeatManager::Start() {
    ScheduleHeartbeat();
}

void HeartbeatManager::Stop() {
    timer_.cancel();
}

void HeartbeatManager::SetInterval(std::chrono::seconds interval) {
    interval_ = interval;
}

void HeartbeatManager::ScheduleHeartbeat() {
    timer_.expires_after(interval_);
    timer_.async_wait([this](const boost::system::error_code& ec) {
        if (ec) {
            if (ec != boost::asio::error::operation_aborted) {
                std::cerr << "Heartbeat timer error: " << ec.message() << std::endl;
            }
            return;
        }

        if (callback_ && !heartbeat_message_.empty()) {
            callback_(heartbeat_message_);
        }

        ScheduleHeartbeat(); // Schedule the next heartbeat
    });
}